package com.df.bpm.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.df.bpm.dto.InformatizationOutputDTO;
import com.df.bpm.dto.InformatizationRequirementBasicDTO;
import com.df.bpm.dto.InformatizationRequirementDetailsDTO;
import com.df.bpm.entity.*;
import com.df.bpm.service.impl.*;
import com.df.common.entity.Pagination;
import com.df.common.exception.BusinessException;
import com.df.common.utils.CommonUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 信息化控制器
 */
@Slf4j
@Tag(name = "信息化控制器")
@RequestMapping("/informatization")
@RequiredArgsConstructor
@RestController
@SaCheckLogin
public class InformatizationController {
    /**
     * 需求申请单基础信息服务
     */
    private final InformatizationRequirementServiceImpl informatizationRequirementServiceImpl;
    /**
     * 需求原因服务
     */
    private final InformatizationReasonServiceImpl informatizationReasonServiceImpl;
    /**
     * 需求预期目标服务
     */
    private final InformatizationTargetServiceImpl informatizationTargetServiceImpl;
    /**
     * 需求预期输出服务
     */
    private final InformatizationOutputServiceImpl informatizationOutputServiceImpl;

    /**
     * 新建需求申请单
     * <P>也可用于增添详情</P>
     * @param detailsDTO 详情（原因、目标、输出物）
     */
    @Operation(summary = "新建需求申请单", description = "新建需求申请单")
    @PostMapping("")
    @SaIgnore
    public ResponseEntity<InformatizationRequirementDetailsDTO> newRequirement(@RequestBody InformatizationRequirementDetailsDTO detailsDTO){
        InformatizationRequirement result=detailsDTO.getBasic();
        if(CommonUtils.varIsBlank(result)){
            throw new BusinessException("申请编号不能为空");
        }
        if(CommonUtils.varIsBlank(result.getNumber())){
            throw new BusinessException("申请编号不能为空");
        }
        if(result.getInformatizationRequirementIndex()==null){
            if(informatizationRequirementServiceImpl.add(result)>0){
                detailsDTO.setBasic(result);
            }else{
                throw new BusinessException("err(informatizationRequirementServiceImpl.add)"+ result);
            }
        }
        return ResponseEntity.ok(informatizationRequirementServiceImpl.addDetailsDTO(detailsDTO));

    }

    /**
     * 按详情dto最终保存
     * @param detailsDTO 详情（原因、目标、输出物）
     */
    @Operation(summary = "按详情dto最终保存", description = "按详情dto最终保存")
    @PutMapping("requirementDetailsDto")
    @SaIgnore
    public ResponseEntity<?> saveRequirementDetailsDto(@RequestBody InformatizationRequirementDetailsDTO detailsDTO){
        informatizationRequirementServiceImpl.saveRequirementDetailsDto(detailsDTO);
        return ResponseEntity.ok(0);
    }

    /**
     * 更新需求申请单
     * <P>各实体类根据自己ID更新，互不影响<P/>
     * @param detailsDTO 详情（原因、目标、输出物）
     */
    @Operation(summary = "更新需求申请单", description = "更新需求申请单")
    @PutMapping("detailsDto")
    @SaIgnore
    public ResponseEntity<Integer> updateRequirement(@RequestBody InformatizationRequirementDetailsDTO detailsDTO){
        int rows=0;
        InformatizationRequirement basic=detailsDTO.getBasic();
        if(CommonUtils.varIsNotBlank(basic)){
            rows+=informatizationRequirementServiceImpl.update(basic);
        }
        List<InformatizationReason> reasons = detailsDTO.getReasons();
        if(CommonUtils.varIsNotBlank(reasons)){
            for (InformatizationReason reason : reasons) {
                rows+=informatizationReasonServiceImpl.update(reason);
            }
        }
        List<InformatizationTarget> targets = detailsDTO.getTargets();
        if(CommonUtils.varIsNotBlank(targets)){
            for (InformatizationTarget target : targets) {
                rows+=informatizationTargetServiceImpl.update(target);
            }
        }
        List<InformatizationOutputDTO> outputs = detailsDTO.getOutputs();
        if(CommonUtils.varIsNotBlank(outputs)){
            for (InformatizationOutput output : outputs) {
                rows+=informatizationOutputServiceImpl.update(output);
            }
        }

        return ResponseEntity.ok(rows);
    }

    /**
     * 删除需求申请单
     * <P>删除basic会连带其它details全部删除<P/>
     * <P>其它details各实体类根据自己ID删除，互不影响<P/>
     * @param detailsDTO 详情（原因、目标、输出物）
     */
    @Operation(summary = "删除需求申请单", description = "按dto删除需求申请单相关详情")
    @PostMapping("deleteDetailsDto")
    @SaIgnore
    public ResponseEntity<Integer> deleteRequirement(@RequestBody InformatizationRequirementDetailsDTO detailsDTO){
        int rows=0;
        InformatizationRequirement basic=detailsDTO.getBasic();
        if(CommonUtils.varIsNotBlank(basic)){
            Integer requirementID=basic.getInformatizationRequirementIndex();
            if(CommonUtils.varIsNotBlank(requirementID)){
                rows+=informatizationRequirementServiceImpl.delete(
                        Collections.singleton(requirementID));
                QueryWrapper<InformatizationReason> wrapper4Reason=new QueryWrapper<>();
                wrapper4Reason.eq("informatizationRequirementIndex", requirementID);
                rows+=informatizationReasonServiceImpl.delete(wrapper4Reason);
                QueryWrapper<InformatizationTarget> wrapper4Target=new QueryWrapper<>();
                wrapper4Target.eq("informatizationRequirementIndex", requirementID);
                rows+=informatizationTargetServiceImpl.delete(wrapper4Target);
                QueryWrapper<InformatizationOutput> wrapper4Output=new QueryWrapper<>();
                wrapper4Output.eq("informatizationRequirementIndex", requirementID);
                rows+=informatizationOutputServiceImpl.delete(wrapper4Output);
            }

        }
        if(rows<1){
            List<InformatizationReason> reasons = detailsDTO.getReasons();
            if(CommonUtils.varIsNotBlank(reasons)){
                List<Integer> reasonIDs=new ArrayList<>();
                for (InformatizationReason reason : reasons) {
                    reasonIDs.add(reason.getInformatizationReasonIndex());
                }
                if(CommonUtils.varIsNotBlank(reasonIDs)){
                    rows+=informatizationReasonServiceImpl.delete(reasonIDs);
                }
            }
            List<InformatizationTarget> targets = detailsDTO.getTargets();
            if(CommonUtils.varIsNotBlank(targets)){
                List<Integer> targetIDs=new ArrayList<>();
                for (InformatizationTarget target : targets) {
                    targetIDs.add(target.getInformatizationTargetIndex());
                }
                if(CommonUtils.varIsNotBlank(targetIDs)){
                    rows+=informatizationTargetServiceImpl.delete(targetIDs);
                }
            }
            List<InformatizationOutputDTO> outputs = detailsDTO.getOutputs();
            if(CommonUtils.varIsNotBlank(outputs)){
                List<Integer> outputIDs=new ArrayList<>();
                for (InformatizationOutput output : outputs) {
                    outputIDs.add(output.getInformatizationOutputIndex());
                }
                if(CommonUtils.varIsNotBlank(outputIDs)){
                    rows+=informatizationOutputServiceImpl.delete(outputIDs);
                }
            }
        }

        return ResponseEntity.ok(rows);
    }

    /**
     * 申请单基础DTO信息模糊查询
     * @param temp 申请单基础DTO
     */
    @Operation(summary = "申请单基础DTO信息模糊查询", description = "申请单基础DTO信息模糊查询")
    @GetMapping("basicDto4Like")
    @SaIgnore
    public ResponseEntity<?> getList4Like(Pagination pagination,InformatizationRequirementBasicDTO temp) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(informatizationRequirementServiceImpl.getList4Like(temp)));
        } else {

            return ResponseEntity.ok(informatizationRequirementServiceImpl.getList4Like(temp));
        }
    }

    /**
     * 信息化申请原因查询
     * @param informatizationRequirementIndex 申请单id
     */
    @Operation(summary = "信息化申请原因查询", description = "信息化申请原因查询")
    @GetMapping("informatizationReason/informatizationRequirementIndex")
    @SaIgnore
    public ResponseEntity<?> getReasons(Pagination pagination,Integer informatizationRequirementIndex) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(
                    informatizationReasonServiceImpl.getList(new InformatizationReason()
                            .setInformatizationRequirementIndex(informatizationRequirementIndex))));
        } else {
            return ResponseEntity.ok(informatizationReasonServiceImpl.getList(new InformatizationReason()
                    .setInformatizationRequirementIndex(informatizationRequirementIndex)));
        }
    }

    /**
     * 信息化目标查询
     * @param informatizationRequirementIndex 申请单id
     */
    @Operation(summary = "信息化目标查询", description = "信息化目标查询")
    @GetMapping("informatizationTarget/informatizationRequirementIndex")
    @SaIgnore
    public ResponseEntity<?> getTargets(Pagination pagination,Integer informatizationRequirementIndex) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(
                    informatizationTargetServiceImpl.getList(new InformatizationTarget()
                            .setInformatizationRequirementIndex(informatizationRequirementIndex))));
        } else {
            return ResponseEntity.ok(informatizationTargetServiceImpl.getList(new InformatizationTarget()
                    .setInformatizationRequirementIndex(informatizationRequirementIndex)));
        }
    }

    /**
     * 信息化输出物查询
     * @param informatizationRequirementIndex 申请单id
     */
    @Operation(summary = "信息化申请原因查询", description = "信息化申请原因查询")
    @GetMapping("informatizationOutput/informatizationRequirementIndex")
    @SaIgnore
    public ResponseEntity<?> getOutputs(Pagination pagination,Integer informatizationRequirementIndex) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(
                    informatizationOutputServiceImpl.getList(new InformatizationOutput()
                            .setInformatizationRequirementIndex(informatizationRequirementIndex))));
        } else {
            return ResponseEntity.ok(informatizationOutputServiceImpl.getList(new InformatizationOutput()
                    .setInformatizationRequirementIndex(informatizationRequirementIndex)));
        }
    }

    /**
     * 信息化申请单完整信息获取
     * @param informatizationRequirementIndex 申请单id
     */
    @Operation(summary = "获取信息化申请详情", description = "获取信息化申请详情")
    @GetMapping("informatizationRequirementDetailsDTO/informatizationRequirementIndex")
    @SaIgnore
    public ResponseEntity<?> getDetailsDto(@RequestParam Integer informatizationRequirementIndex) {
        return ResponseEntity.ok(informatizationRequirementServiceImpl
                .getDetailsDto(informatizationRequirementIndex));
    }


}
